package com.z.common;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Scanner;

public class MyBatisGenerator {
    public static void main(String[] args) {
        AutoGenerator ag = new AutoGenerator();
        GlobalConfig gc = new GlobalConfig();
        String path = System.getProperty("user.dir");
        gc.setOutputDir(path+"/src/main/java");
        gc.setSwagger2(true);
        gc.setAuthor("zxy");
        gc.setOpen(false);
        ag.setGlobalConfig(gc);


        DataSourceConfig ds = new DataSourceConfig();
        ds.setDriverName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        ds.setUsername("root");
        ds.setPassword("12345678");
        ag.setDataSource(ds);

        PackageConfig p = new PackageConfig();
        p.setModuleName(scanner("模块名"));
        p.setParent("com.z");
        p.setController("controller");
        p.setService("service");
        p.setServiceImpl("service.impl");
        p.setMapper("mapper");
        p.setEntity("model");
        ag.setPackageInfo(p);

        StrategyConfig s = new StrategyConfig();
        s.setTablePrefix(scanner("表前缀"));
        s.setControllerMappingHyphenStyle(true);
        s.setInclude(scanner("表名，英文逗号隔开").split(","));
        s.setColumnNaming(NamingStrategy.underline_to_camel);
        s.setNaming(NamingStrategy.underline_to_camel);
        s.setEntitySerialVersionUID(true);
        s.setEntityTableFieldAnnotationEnable(true);
        ag.setStrategy(s);
        ag.setTemplateEngine(new FreemarkerTemplateEngine());
        ag.execute();
    }

    private static String scanner(String s) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入" + s + ":");
        if(sc.hasNext()){
            String instr = sc.next();
            if(StringUtils.isNotBlank(instr)){
                return instr;
            }
        }
        throw new MybatisPlusException("输入异常");
    }
}